package com.syni.mdd.yhd.common.all.service;

import com.alibaba.fastjson.JSON;
import com.syni.mdd.sjb.common.component.utils.common.utils.BeanUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.DateTimeUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.constants.ResultMsg;
import com.syni.mdd.yhd.common.all.dao.jpa.BmsBusinessGroupMessageDao;
import com.syni.mdd.yhd.common.all.entity.*;
import com.syni.mdd.yhd.common.all.entity.user.BmsUser;
import com.syni.mdd.yhd.common.all.listen.groupMessage.GroupMessageEvent;
import com.syni.mdd.yhd.common.all.quartz.QuartzDo;
import com.syni.mdd.yhd.common.all.quartz.groupMessage.GroupMessageJobListener;
import com.syni.mdd.yhd.common.all.quartz.groupMessage.GroupMessageTimingJob;
import com.syni.mdd.yhd.common.all.service.impl.BaseService;
import com.syni.mdd.yhd.common.all.utils.*;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.map.HashedMap;
import org.quartz.*;
import org.quartz.impl.matchers.KeyMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.DependsOn;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @className
 * @description TOO
 * @Author cfx
 * @DATE 2019/4/9 12:04
 * @VERSION 1.0
 **/
@Log4j2
@Service
@DependsOn("applicationContextHolder")
public class BmsBusinessGroupMessageService extends BaseService<BmsBusinessGroupMessage, Integer> {

    //每个用户每月最多4条
    @Value("${MAX_SEND:4}")
    public int MAX_SEND;
    //失败状态
    public final static int SEND_FAIL = 2;
    final static String JOB_NAME = "job_message_id_";
    final static String TRI_NAME = "tri_message_id_";
    final static String DEFAULT_JOB_GROUOP = "me_job_group";
    final static String DEFAULT_TRI_GROUOP = "me_tri_group";
    final static String JOB_CALLBACK = "job_callBack_";

    @Autowired
    BmsBusinessGroupMessageDao bmsBusinessGroupMessageDao;

    @Autowired
    BmsUserBusinessAuthService bmsUserBusinessAuthService;

    @Autowired
    BmsBusinessService bmsBusinessService;

    @Autowired
    BmsDxNewsService bmsDxNewsService;

    @Autowired
    BmsUserReceGroupMessageService bmsUserReceGroupMessageService;

    @Autowired
    BmsUserBusinessFocusService bmsUserBusinessFocusService;

    @Autowired
    BmsDxOrderService bmsDxOrderService;

    @Autowired
    BmsUserBusinessService bmsUserBusinessService;

    @Autowired
    BmsDxOrderStatusService bmsDxOrderStatusService;

    @Autowired
    BmsMarketActivityService bmsMarketActivityService;

    @Autowired
    BmsBusinessCouponService bmsBusinessCouponService;

    @Autowired
    BmsUserService bmsUserService;


    @Override
    public BmsBusinessGroupMessageDao getBaseDao() {
        return bmsBusinessGroupMessageDao;
    }

    public Integer getThisMonthSendNum(Integer businessId,Integer sendType){
        Date nowTime = new Date();
        Integer startTime = (int)(DateTimeUtils.getFirstDayOfMonth(nowTime).getTime() / 1000);
        Integer endTime = (int)(DateTimeUtils.getLastDayOfMonth(nowTime).getTime() / 1000);
        return bmsBusinessGroupMessageDao.selfFindBusinessSendNum(businessId,sendType,startTime,endTime);
    }

    public Map<String, Object> createBefore(Integer userId,Integer businessId,Integer sendType) {
        Integer businessSendNum = getThisMonthSendNum(businessId,sendType);
        if(businessSendNum >= MAX_SEND){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_GROUP_MESSAGE_MAX,"本月发送信息数量已达到上限");
        }
        return ResultMapHelper.success(null,"ok");
    }

    @Transactional
    public Map<String, Object> create(Integer userId, Integer businessId, String sendUser, String content,
                                      Integer sendType,String regularlySend,Boolean choseAll,Integer activityId,
                                      Integer businessCouponId) {
        //查询该用户是不是认领该商家
        Map<String,Object> checkMap = bmsUserBusinessService.checkBusinessIsHaving(userId,businessId);
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        BmsBusiness business = (BmsBusiness) checkMap.get("data");
        if(business.getIsAuth() == Constants.COMMON_FLAG_FALSE_INT){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_AUTH,"店铺未认证");
        }
        //查询该用户是否发送上限
        Integer sendNum = getThisMonthSendNum(businessId,sendType);
        if(sendNum >= MAX_SEND){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_GROUP_MESSAGE_MAX,"本月发送信息数量已达到上限");
        }
        Date nowDate = new Date();
        List<String> sendUsers = new LinkedList<>();
        if(choseAll){
            if(sendType == Constants.SEND_TO_FOCUS) {
                //查询所有粉丝
                List<BmsUserBusinessFocus> bmsUserBusinessFocusList = bmsUserBusinessFocusService.getBusinessFoces(businessId);
                if (bmsUserBusinessFocusList != null && bmsUserBusinessFocusList.size() > 0) {
                    for (BmsUserBusinessFocus bmsUserBusinessFocus : bmsUserBusinessFocusList) {
                        sendUsers.add(bmsUserBusinessFocus.getBmsUserId().toString());
                    }
                }
            }else if(sendType == Constants.SEND_TO_CONSUMER){
                //查询所有消费者
                List<Map> consumerUsers = bmsDxOrderStatusService.getBusinessConsumerUsers(businessId);
                if (consumerUsers != null && consumerUsers.size() > 0) {
                    for (Map<String,Object> consumerUser : consumerUsers) {
                        sendUsers.add(consumerUser.get("userId").toString());
                    }
                }
            }
        }else {
            sendUsers = Arrays.asList(sendUser.split("_"));
        }
        if(!(sendUsers.size() > 0)){
            return ResultMapHelper.failure("发送用户不能为空");
        }
        BmsBusinessGroupMessage bmsBusinessGroupMessage = new BmsBusinessGroupMessage();
        bmsBusinessGroupMessage.setBmsBusinessId(businessId);
        bmsBusinessGroupMessage.setContent(content);
        bmsBusinessGroupMessage.setMesType(Constants.GROUP_SEND_TYPE_GEN);
        if(activityId != null){
            BmsMarketActivity bmsMarketActivity = bmsMarketActivityService.findById(activityId);
            if(bmsMarketActivity != null){
                bmsBusinessGroupMessage.setMesType(Constants.GROUP_SEND_TYPE_MARKET);
                bmsBusinessGroupMessage.setContent(JSON.toJSONString(bmsMarketActivity));
            }
        }
        if(businessCouponId != null){
            BmsBusinessCoupon businessCoupon = bmsBusinessCouponService.getBaseDao().findByIdAndIsDelete(businessCouponId,Constants.COMMON_FLAG_FALSE_INT);
            if(businessCoupon != null){
                bmsBusinessGroupMessage.setMesType(Constants.GROUP_SEND_TYPE_COUPON);
                bmsBusinessGroupMessage.setContent(JSON.toJSONString(businessCoupon));
            }
        }
        bmsBusinessGroupMessage.setActivityId(activityId);
        bmsBusinessGroupMessage.setType(sendType);
        bmsBusinessGroupMessage.setNewTime(DateTimeUtils.converLongToDate(nowDate.getTime() + 1));
        bmsBusinessGroupMessage.setReceNum(sendUsers.size());
        bmsBusinessGroupMessage.setReceUser(StringUtils.join(sendUsers,"_"));
        bmsBusinessGroupMessage.setIsDelete(Constants.COMMON_FLAG_FALSE_INT);
        if(regularlySend == null){
            bmsBusinessGroupMessage.setStatus(Constants.COMMON_FLAG_TRUE_INT);
            if(businessCouponId != null){
                //需要再发一条文本消息
                sendText(bmsBusinessGroupMessage,content,sendUsers);
            }
            bmsBusinessGroupMessageDao.save(bmsBusinessGroupMessage);
            //往消息子表添加发送信息
            Set<Integer> userIds = doSendUserOp(businessId,bmsBusinessGroupMessage,sendUsers);
            //往消息表发送消息
            addGroupMessageToNews(business,userIds,bmsBusinessGroupMessage);
        }else {
            //定时发送
            Date startDate = DateTimeUtils.converStringToDate(regularlySend,DateTimeUtils.DATE_PATTERN_TIMESTAMP_02);
            Integer startTime = (int)(startDate.getTime() / 1000);
            Integer nowTime = (int)(nowDate.getTime() / 1000);
            if(startTime < nowTime){
                return ResultMapHelper.result(ResultCode.CODE_BUSINESS_GROUP_MESSAGE_QUARTZ_ERROR,"时间设置不合理");
            }
            int times = startTime - nowTime;
            if(times > 30 * 3600 * 24){
                return ResultMapHelper.result(ResultCode.CODE_BUSINESS_GROUP_MESSAGE_QUARTZ_MAX,"定时短信超过30天");
            }
            bmsBusinessGroupMessage.setStatus(Constants.COMMON_FLAG_FALSE_INT);
            bmsBusinessGroupMessage.setRegularlySend(DateTimeUtils.converDateToString(startDate,DateTimeUtils.DATE_PATTERN_TIMESTAMP_02));
            if(businessCouponId != null){
                //需要再发一条文本消息
                BmsBusinessGroupMessage bs = sendText(bmsBusinessGroupMessage,content,sendUsers);
                this.doGroupMessageTiming(GroupMessageTimingJob.class,startDate,bs,sendUsers);
            }
            bmsBusinessGroupMessageDao.save(bmsBusinessGroupMessage);
            //往消息子表添加发送信息
            doSendUserOp(businessId,bmsBusinessGroupMessage,sendUsers);
            this.doGroupMessageTiming(GroupMessageTimingJob.class,startDate,bmsBusinessGroupMessage,sendUsers);
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("receUserNum",sendUsers.size());
        sendNum = getThisMonthSendNum(businessId,sendType);
        resultMap.put("remainSendNum",MAX_SEND - sendNum);
        resultMap.put("sendData",bmsBusinessGroupMessage);
        log.info("remainSendNum:{}",MAX_SEND - sendNum);
        return ResultMapHelper.success(resultMap,"发送成功");
    }

    /**
     * @Description 发送普通的文本附加消息
     * @Author: cfx
     * @Date: 2019/11/5
     */
    public BmsBusinessGroupMessage sendText(BmsBusinessGroupMessage bmsBusinessGroupMessage,String content,List<String> sendUsers){
        BmsBusinessGroupMessage bs = new BmsBusinessGroupMessage();
        BeanUtils.copyProperties(bmsBusinessGroupMessage,bs);
        bs.setMesType(Constants.GROUP_SEND_TYPE_GEN);
        bs.setContent(content);
        bmsBusinessGroupMessageDao.save(bs);
        //往消息子表添加发送信息
        doSendUserOp(bmsBusinessGroupMessage.getBmsBusinessId(),bs,sendUsers);
        return bs;
    }

    public void doGroupMessageTiming(Class classes,Date startDate,
                                     BmsBusinessGroupMessage bmsBusinessGroupMessage,List<String> sendUsers){
        Integer groupMessageId = bmsBusinessGroupMessage.getId();
        String jobName = JOB_NAME + groupMessageId;
        String triggerName = TRI_NAME + groupMessageId;
        String groupJobName = DEFAULT_JOB_GROUOP + groupMessageId;
        String triggerJobName = DEFAULT_TRI_GROUOP + groupMessageId;
        String callbackName = JOB_CALLBACK + groupMessageId;
        try {
            JobDetail job1 = JobBuilder.newJob(classes)
                    .withIdentity(jobName,groupJobName)
                    .build();
            job1.getJobDataMap().put("bmsBusinessGroupMessage",bmsBusinessGroupMessage);
            job1.getJobDataMap().put("sendUsers",sendUsers);
            SimpleTrigger trigger1 = (SimpleTrigger) TriggerBuilder.newTrigger()
                    .withIdentity(triggerName, triggerJobName)
                    //.forJob("jog1", "group1")                 // identify job with name, group strings
                    .startAt(startDate)
                    .build();
            Matcher<JobKey> matcher = KeyMatcher.keyEquals(job1.getKey());
            QuartzDo.addJobToScheduler(job1,trigger1);
            GroupMessageJobListener groupMessageJobListener = new GroupMessageJobListener(callbackName);
            QuartzDo.getScheduler().getListenerManager().addJobListener(groupMessageJobListener,matcher);
            QuartzDo.getScheduler().start();
        } catch (SchedulerException e) {
            log.error(e.getMessage(),e);
        }
    }

    public Set<Integer> doSendUserOp(Integer businessId,BmsBusinessGroupMessage bmsBusinessGroupMessage,List<String> sendUsers){

        Set<Integer> userIds = new HashSet<>();
        List<BmsUserReceGroupMessage> bmsUserReceGroupMessagesList = new LinkedList<>();
        //查出关注时间
        Map<Integer,BmsUserBusinessFocus> bmsUserBusinessFocusMap = new HashedMap();
        if(bmsBusinessGroupMessage.getMesType() == Constants.SEND_TO_FOCUS){
            bmsUserBusinessFocusMap = bmsUserBusinessFocusService.getMapByUserIdsAndBusinessId(sendUsers,businessId);
        }
        for(String user : sendUsers){
            Integer tmpUserId = Integer.parseInt(user);
            userIds.add(tmpUserId);
            BmsUserReceGroupMessage bmsUserReceGroupMessage = new BmsUserReceGroupMessage();
            bmsUserReceGroupMessage.setBmsUserId(tmpUserId);
            bmsUserReceGroupMessage.setGroupMessageId(bmsBusinessGroupMessage.getId());
            bmsUserReceGroupMessage.setIsRead(Integer.parseInt(Constants.COMMON_FLAG_FALSE));
            bmsUserReceGroupMessage.setStatus(Constants.COMMON_FLAG_TRUE_INT);
            if(bmsUserBusinessFocusMap.containsKey(tmpUserId)){
                bmsUserReceGroupMessage.setNewTime(bmsUserBusinessFocusMap.get(tmpUserId).getNewTime());
            }
            if(StringUtils.isNotBlank(bmsBusinessGroupMessage.getRegularlySend())){
                bmsUserReceGroupMessage.setStatus(Constants.COMMON_FLAG_FALSE_INT);
            }
            bmsUserReceGroupMessagesList.add(bmsUserReceGroupMessage);
        }
        bmsUserReceGroupMessageService.getBaseDao().saveAll(bmsUserReceGroupMessagesList);
        return userIds;
    }



    public Map<String,Object> findBusinessGroupMessage(Integer userId,Integer businessId,Integer type,
                                                       Integer pageNum,Integer pageSize){
        //查询该用户是不是认领该商家
        Map<String,Object> checkMap = bmsUserBusinessService.checkBusinessIsHaving(userId,businessId);
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        Optional<BmsBusiness> bmsBusinessOptional = bmsBusinessService.getBaseDao().findById(businessId);
        if(!bmsBusinessOptional.isPresent()){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_EXIST,"店铺不存在");
        }
        Pageable pageable = BmsCommonService.getPageable(pageNum,pageSize, Sort.Direction.DESC,"newTime");
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("bmsBusinessId",businessId);
        conditionMap.put("type",type);
        conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
        List<BmsBusinessGroupMessage> bmsBusinessGroupMessages = bmsBusinessGroupMessageDao.findAll(new SpecificationUtils(conditionMap),pageable).getContent();
        postHandleReceUserHeadImg(bmsBusinessGroupMessages);
        return ResultMapHelper.success(bmsBusinessGroupMessages,ResultMsg.MSG_GET_SUCCESS);
    }

    private void postHandleReceUserHeadImg(List<BmsBusinessGroupMessage> bmsBusinessGroupMessages) {
        if(bmsBusinessGroupMessages != null){
            for(BmsBusinessGroupMessage bmsBusinessGroupMessage : bmsBusinessGroupMessages){
                List<String> headImgList = new LinkedList<>();
                String[] userIdsArray = bmsBusinessGroupMessage.getReceUser().split("_");
                for(int ii = 0;ii < 3;ii++){
                    if(userIdsArray.length - 1 >= ii) {
                        BmsUser bmsUser = TokenManager.getUser(Integer.parseInt(userIdsArray[ii]));
                        if(bmsUser != null){
                            headImgList.add(BmsUserService.getHeadImg(bmsUser));
                        }
                    }
                }
                bmsBusinessGroupMessage.setReceUserHeadImg(JSON.toJSONString(headImgList));
            }
        }

    }


    @Transactional
    public Map<String,Object> findUserGroupMessage(Integer userId,Integer businessId,
                                                   Integer pageNum,Integer pageSize){
        Optional<BmsBusiness> bmsBusinessOptional = bmsBusinessService.getBaseDao().findById(businessId);
        if(!bmsBusinessOptional.isPresent()){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_EXIST,"店铺不存在");
        }
        BmsBusiness business = bmsBusinessOptional.get();
        Map<String,Object> businessMap = new HashMap<>();
        businessMap.put("logoUrl",business.getLogoUrl());
        businessMap.put("vendorName",business.getVendorName());
        businessMap.put("id",business.getId());
        List<Map<String,Object>> bmsBusinessGroupMessages;
        Pageable pageable = BmsCommonService.getPageable(pageNum,pageSize, Sort.Direction.DESC,"new_time");
        bmsBusinessGroupMessages = bmsBusinessGroupMessageDao.selfFindUserBusinessMessage(userId,businessId,pageable);
        if(bmsBusinessGroupMessages != null && bmsBusinessGroupMessages.size() > 0){
            Set<Integer>  burgmIds = new HashSet<>();
            for(Map<String,Object> objectMap : bmsBusinessGroupMessages){
                Integer burgmId = Integer.parseInt(objectMap.get("burgmId").toString());
                burgmIds.add(burgmId);
            }
            if(burgmIds.size() > 0){
                bmsUserReceGroupMessageService.getBaseDao().selfUpdateUserMessageToRead(burgmIds);
            }
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("business",businessMap);
        resultMap.put("messageData",bmsBusinessGroupMessages);
        return ResultMapHelper.success(resultMap,ResultMsg.MSG_GET_SUCCESS);
    }

    public void addGroupMessageToNews(BmsBusiness bmsBusiness,Set<Integer> sendUserIds,BmsBusinessGroupMessage bmsBusinessGroupMessage){
        /*Map<String,Object> content = new HashMap<>();
        content.put("activityId",bmsBusinessGroupMessage.getActivityId());
        content.put("content",bmsBusinessGroupMessage.getContent());*/
        String content = bmsBusinessGroupMessage.getContent();
        if(bmsBusinessGroupMessage.getMesType() == Constants.GROUP_SEND_TYPE_GEN){

        }else if(bmsBusinessGroupMessage.getMesType() == Constants.GROUP_SEND_TYPE_MARKET){
            Map<String,Object> activityData = JSON.parseObject(content);
            content = String.format("有新的活动：%s",activityData.get("activityName"));
        }else if(bmsBusinessGroupMessage.getMesType() == Constants.GROUP_SEND_TYPE_COUPON){
            Map<String,Object> couponData = JSON.parseObject(content);
            content = String.format("有新的优惠券：%s",couponData.get("couponName"));
        }
        BmsCommonService.getApplicationContext().publishEvent(new GroupMessageEvent("groupMessage",bmsBusiness,sendUserIds,content));
        /*Optional<BmsBusiness> bmsBusinessOp = bmsBusinessService.getBaseDao().findById(businessId);
        if(!bmsBusinessOp.isPresent()){
            return;
        }
        BmsBusiness business = bmsBusinessOp.get();
        //查出要发送的用户的消息
        Map<Integer,BmsDxNews> bmsDxNewsMap = getBmsNewMapByUserIdAndBusinessId(businessId,sendUserIds);
        Date nowTime = new Date();
        if(sendUserIds.size() > 0) {
            List<BmsDxNews> bmsDxNewsList = new LinkedList<>();
            for(Integer userId : sendUserIds){
                BmsDxNews bmsDxNews;
                if(bmsDxNewsMap.containsKey(userId)){
                    bmsDxNews = bmsDxNewsMap.get(userId);
                    bmsDxNews.setTitile(business.getVendorName());
                    bmsDxNews.setContent(content);
                    bmsDxNews.setOriginRole(Constants.GENERAL_USER_ROLE_ID);
                    bmsDxNews.setUpdateTime(nowTime);
                }else {
                    bmsDxNews = new BmsDxNews();
                    bmsDxNews.setBmsUserId(userId);
                    bmsDxNews.setBmsBusinessId(businessId);
                    bmsDxNews.setParentType(BmsDxNewsService.PARENTTYPT_PRO);
                    bmsDxNews.setChildType(BmsDxNewsService.PARENTTYPT_PRO_ORDINARY);
                    bmsDxNews.setTitile(business.getVendorName());
                    bmsDxNews.setContent(content);
                    bmsDxNews.setBusinessImg(business.getLogoUrl());
                    bmsDxNews.setNewTime(nowTime);
                    bmsDxNews.setUpdateTime(nowTime);
                    //bmsDxNews.setFromOrigin(Constants.USER_CLIENT);
                    bmsDxNews.setOriginRole(Constants.GENERAL_USER_ROLE_ID);
                }
                bmsDxNewsList.add(bmsDxNews);
            }
            bmsDxNewsService.getBaseDao().saveAll(bmsDxNewsList);
            Set<String> sendUsers = new HashSet<>();
            for(Integer userId : sendUserIds){
                sendUsers.add(AuroraPushUtils.USER_PREFIX + userId.toString());
            }
            //进行极光推送
            String alert = String.format(AuroraPushCode.pushTemplateMap.get(AuroraPushCode.USER_RECE_GROUP_MES).getAlert(),bmsDxNewsList.get(0).getTitile());
            BmsCommonService.pushToFront(bmsDxNewsList.get(0),AuroraPushCode.USER_RECE_GROUP_MES,alert,sendUsers.toArray(new String[sendUsers.size()]));
        }*/
    }

    public Map<Integer,BmsDxNews> getBmsNewMapByUserIdAndBusinessId(Integer businessId,Set<Integer> userIds){
        Map<Integer,BmsDxNews> resultMap = new HashMap<>();
        if(userIds.size() > 0){
            Map<String,Object> conditionMap = new HashMap<>();
            conditionMap.put("bmsUserId_IN",userIds);
            conditionMap.put("bmsBusinessId",businessId);
            conditionMap.put("parentType",BmsDxNewsService.PARENTTYPT_PRO);
            conditionMap.put("childType",BmsDxNewsService.PARENTTYPT_PRO_ORDINARY);
            List<BmsDxNews> bmsDxNewsList = bmsDxNewsService.getBaseDao().findAll(new SpecificationUtils(conditionMap));
            if(bmsDxNewsList != null && bmsDxNewsList.size() > 0){
                for(BmsDxNews bmsDxNews : bmsDxNewsList){
                    resultMap.put(bmsDxNews.getBmsUserId(),bmsDxNews);
                }
            }
        }
        return resultMap;
    }

    public Map<String, Object> findGroupMessageUser(Map<String,Object> paramsMap) {
        Integer groupMessageId = Integer.parseInt(paramsMap.get("group_message_id").toString());
        Integer userId = Integer.parseInt(paramsMap.get("userIdentify").toString());
        Integer businessId = Integer.parseInt(paramsMap.get("business_id").toString());
        Integer pageNum = Integer.parseInt(paramsMap.get("page_num").toString());
        Integer pageSize = Integer.parseInt(paramsMap.get("page_size").toString());
        Map<String,Object> checkMap = bmsUserBusinessService.checkBusinessIsHaving(userId,businessId);
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        BmsBusinessGroupMessage bmsBusinessGroupMessage = bmsBusinessGroupMessageDao.findByIdAndIsDelete(groupMessageId,Constants.COMMON_FLAG_FALSE_INT);
        if(bmsBusinessGroupMessage == null){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_GROUP_MESSAGE_NO_EXIST,ResultMsg.CODE_BUSINESS_GROUP_MESSAGE_NO_EXIST);
        }
        Pageable pageable = BmsCommonService.getPageable(pageNum,pageSize);
        List userList = new LinkedList<>();
        //判断消息类型
        List<BmsUserReceGroupMessage> bmsUserReceGroupMessages = bmsUserReceGroupMessageService.getBaseDao().findByGroupMessageId(groupMessageId,pageable);
        Set<Integer> userIds = new HashSet<>();
        if(bmsUserReceGroupMessages != null && bmsUserReceGroupMessages.size() > 0){
            for(BmsUserReceGroupMessage bmsUserReceGroupMessage : bmsUserReceGroupMessages){
                userIds.add(bmsUserReceGroupMessage.getBmsUserId());
            }
        }
        if(userIds.size() > 0){
            if(bmsBusinessGroupMessage.getType() == Constants.SEND_TO_FOCUS){
                userList.addAll(bmsUserReceGroupMessageService.getBaseDao().sendGroupMessageRece(groupMessageId,userIds));
            }else if(bmsBusinessGroupMessage.getType() == Constants.SEND_TO_CONSUMER){
                userList.addAll(bmsUserBusinessService.setConsumerUser(bmsDxOrderStatusService.getBusinessConsumerUsers(businessId,userIds)));
            }
        }
        return ResultMapHelper.success(userList,ResultMsg.MSG_GET_SUCCESS);
    }

    public Map<String, Object> repeatCreate(Integer userId, Integer businessId,Integer groupMessageId,
                                            String content,String regularlySend) {
        //找到之前的消息记录
        Optional<BmsBusinessGroupMessage> bmsBusinessGroupMessageOp = bmsBusinessGroupMessageDao.findById(groupMessageId);
        if(!bmsBusinessGroupMessageOp.isPresent()){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_GROUP_MESSAGE_NO_EXIST,"消息不存在");
        }
        BmsBusinessGroupMessage bmsBusinessGroupMessage = bmsBusinessGroupMessageOp.get();
        //找出当前群发消息的发送用户
        String sendUser = bmsBusinessGroupMessage.getReceUser();
        return create(userId,businessId,sendUser,content,bmsBusinessGroupMessage.getType(),
                regularlySend,false,bmsBusinessGroupMessage.getActivityId(),null);
        //return null;
    }

    /**
     * @Description 获取群发展示页,关注人数和消费者人数
     * @Author: cfx
     * @Date: 2019/7/5
     */
    public Map<String, Object> createHome(Integer userId, Integer businessId) {
        Map<String,Object> checkMap = bmsUserBusinessService.checkBusinessIsHaving(userId,businessId);
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        Map<String,Object> resultMap = new HashMap<>();
        //查询关注人数
        resultMap.put("focusNum",bmsUserBusinessFocusService.getBaseDao().selfFindBusinessFocusNum(businessId));
        //查询消费者人数
        resultMap.put("consumerNum",bmsDxOrderStatusService.getBusinessConsumerUsersNum(businessId));
        return ResultMapHelper.success(resultMap,ResultMsg.MSG_GET_SUCCESS);
    }

    public void doSendUserOpByTiming(BmsBusinessGroupMessage bmsBusinessGroupMessage) {
        List<BmsUserReceGroupMessage> bmsUserReceGroupMessages = bmsUserReceGroupMessageService.getBaseDao().findByGroupMessageId(bmsBusinessGroupMessage.getId());
        if(bmsBusinessGroupMessage != null && bmsUserReceGroupMessages.size() > 0){
            for(BmsUserReceGroupMessage bmsUserReceGroupMessage : bmsUserReceGroupMessages){
                bmsUserReceGroupMessage.setStatus(Constants.COMMON_FLAG_TRUE_INT);
            }
            bmsUserReceGroupMessageService.getBaseDao().saveAll(bmsUserReceGroupMessages);
        }
    }
}
